package com.wky.example.dao.impl;

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.wky.common.util.Tools;
import com.wky.example.dao.IUserDao;
import com.wky.example.entity.User;

public class UserDaoImpl extends HibernateDaoSupport implements IUserDao {

	public Long addUser(User user) {
		return (Long) this.getHibernateTemplate().save(user);
	}

	public void deleteUser(User user) {
		this.getHibernateTemplate().delete(user);
	}

	@SuppressWarnings("unchecked")
	public List<User> findUserList(User user) {
		
		Object[] values = new Object[50];
		int idx = 0;
		
		StringBuffer hql = new StringBuffer();
		hql.append("from ").append(User.class.getName()).append(" as u where 1=1 ");
		
		if(Tools.isNotEmptyString(user.getName())){
			hql.append(" and u.name like ? ");
			values[idx++] = "%" + user.getName() + "%";
		}
		
		if(user.getAge() != null){
			hql.append(" and u.age = ? ");
			values[idx++] =  user.getAge() ;
		}
		
		if (idx > 0) {
			Object[] condition = new Object[idx];
			System.arraycopy(values, 0, condition, 0, idx);
			return this.getHibernateTemplate().find(hql.toString(),condition);
		}
		return this.getHibernateTemplate().find(hql.toString());
	}

	public void updateUser(User user) {
		this.getHibernateTemplate().saveOrUpdate(user);
		this.getHibernateTemplate().flush();
	}

	public User findUser(Long id) {
		return this.getHibernateTemplate().load(User.class, id);
	}

}
